package com.bigtomato.tomatochat.server;

import com.google.gson.Gson;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServer {
    //private Session session;//与某个客户端的连接会话，需要通过它来给客户端发送数据
    public List<Session> sessions=new LinkedList<>();
    private String userId;
    private WebSocketServer otherUser;
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        System.out.println("user"+userId+"加入");
        this.userId=userId;
        this.sessions.add(session);
        Map<String,String> map=new HashMap<>();
        map.put("state","updateUserList");
        int i=0;
        for (Map.Entry<String, WebSocketServer> user : UserMapServer.users.entrySet()) {
            if(!user.getKey().equals(userId)){
                map.put("user"+i,user.getKey());
                i++;
            }
        }
        Gson gson=new Gson();
        String message=gson.toJson(map);
        System.out.println(message);
        sendMessage(message);//更新自己的好友列表
        UserMapServer.add(userId,this);
    }
    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("接收到客户端发过来的消息："+message);
        Gson gson=new Gson();
        Map<String, String> map = new HashMap<String, String>();
        map = gson.fromJson(message, map.getClass());
        if(map.get("accepter").equals("公共聊天室")){
            UserMapServer.broadCast(map.get("sender"),message);
        }else{
            UserMapServer.sendMessage(map.get("accepter"),message);
        }
    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
    @OnClose
    public void onClose(Session session){
        System.out.println("有链接关闭");
        UserMapServer.remove(userId,session);
    }
    public void sendMessage(String message) {
        try {
            for(Session session:sessions) {
                session.getBasicRemote().sendText(message);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
